import React, { Component } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
// 引入context,拿到Provider.传递editId
import context from './context'
import './App.css'
export default class App extends Component {
  state = {
    todos: JSON.parse(localStorage.getItem('todos')) || [],
    editId: undefined, //默认值undefined,表示没有任何一个Item要进行编辑. 如果值是某个Item的id.则对应的Item组件展示编辑的文本框
  }

  componentDidMount() {
    // 订阅添加的话题
    this.addId = PubSub.subscribe('add', (_, todoName) => {
      const todo = {
        id: Date.now(),
        todoName,
        isDone: false,
      }

      this.state.todos.push(todo)

      this.setState({
        todos: this.state.todos,
      })
    })

    // 订阅修改editId的话题
    this.setEditId = PubSub.subscribe('editId', (_, id) => {
      this.setState({
        editId: id,
      })
    })
    // 订阅修改指定任务的任务名的话题
    this.setTodoName = PubSub.subscribe(
      'setTodoName',
      // 只接在形参这里结构传过来的对象
      (_, { id, todoName }) => {
        this.state.todos.forEach((item) => {
          if (item.id === id) item.todoName = todoName
        })

        this.setState({
          todos: this.state.todos,
          editId: undefined,
        })
      }
    )
  }

  componentWillUnmount() {
    // 组件卸载清除订阅
    PubSub.unsubscribe(this.addId)
    PubSub.unsubscribe(this.setEditId)
    PubSub.unsubscribe(this.setTodoName)
  }
  render() {
    const { editId } = this.state
    return (
      <context.Provider value={editId}>
        <div className="todo-container">
          <div className="todo-wrap">
            <Header></Header>
            <div>
              <List todos={this.state.todos}></List>
              <Footer></Footer>
            </div>
          </div>
        </div>
      </context.Provider>
    )
  }
  componentDidUpdate() {
    localStorage.setItem('todos', JSON.stringify(this.state.todos))
  }
}
